//
//  StatusPictureView.swift
//  Weibo
//
//  Created by 孙成宇 on 15/12/1.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

// 2. 配图视图格子间距  定义可重用 Cell 标识符
private let pictureCellID = "pictureCellID"


private let pictureCellMargin : CGFloat = 5

class StatusPictureView: UICollectionView {
   
   //MARK: <##>3.在配图视图中定义视图模型属性

    
    var imageURLs: [NSURL]? {
        didSet {
            if imageURLs != nil{
            
            textLabel.text = "\(imageURLs!.count)"
            }
            let pSize = caclePictureViewSize()
            self.snp_updateConstraints { (make) -> Void in

                make.width.equalTo(pSize.width)
                make.height.equalTo(pSize.height)
            }
            
            reloadData()
    }
    
    }
     //MARK: 计算itenSIze 尺寸
    private func caclePictureViewSize() ->CGSize {
    
    
    let imageCount = imageURLs?.count ?? 0
        let maxWidth = screenW - 2 * StatusCellMargin
        let itemWidth = (maxWidth - 2 * pictureCellMargin) / 3.001
        
        //设置cell的大小
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        
        
        if imageCount == 0 {
        return CGSizeZero
        }
        
        if imageCount == 1 {
        var imageSize = CGSizeMake(180, 120)

let key = imageURLs?.first?.absoluteString ?? ""
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            if image != nil {

imageSize = image.size
            }
            imageSize.width = imageSize.width > maxWidth ? maxWidth : imageSize.width
            imageSize.height = imageSize.height > 250 ? 250 : imageSize.height



            layout.itemSize = imageSize
            return imageSize
            
        }
        if imageCount == 4 {

        let pW = itemWidth * 2.01 + pictureCellMargin
            return CGSizeMake(pW, pW)
            
        }
    let row = CGFloat((imageCount - 1 )/3  + 1)
        return CGSizeMake(maxWidth, itemWidth * row + pictureCellMargin * (row - 1 ))
    
    }
    
    
    
    // MARK: 1. 构造函数
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
     
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin

        
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        //注册cell
        registerClass(PictureCell.self, forCellWithReuseIdentifier: pictureCellID)
        
        
        //设置数据源
        dataSource = self
        backgroundColor = UIColor.randomColor()
           setUI()
    }
    
    private func setUI(){
    addSubview(textLabel)
        textLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.center)
            
        }
    
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //懒加载label
    private lazy var textLabel: UILabel = UILabel(title: "", color: UIColor.redColor(), fontSize: 30, margin: 0)
    

}

//MARK : 数据源方法
extension StatusPictureView : UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! PictureCell
        
        
        //返回 Cell，设置图像
                cell.imageURL = imageURLs![indexPath.item]
        return cell
        
       }

}



//    Cell UI 准备
class PictureCell: UICollectionViewCell  {
   
    var imageURL: NSURL? {
        didSet {
       iconView.sd_setImageWithURL(imageURL)
        
        }
        
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI () {
    
    contentView.addSubview(iconView)
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
    
    }
    
    
     //MARK: 图片填充模式
    private lazy var iconView:  UIImageView = {
 
        let iv = UIImageView()
    
        iv.clipsToBounds = true
    
        iv.contentMode = .ScaleAspectFill
        return iv
        
    
    
    
    }()
}



